package com.cyou.qb.face.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cyou.fz173.util.Jackson2Util;
import com.cyou.fz173.util.JacksonUtil;
import com.cyou.qb.face.entity.Face173AccessLog;
import com.cyou.qb.face.entity.GameInfo;
import com.cyou.qb.face.entity.NameValue;
import com.cyou.qb.face.entity.OutService;
import com.cyou.qb.face.entity.VideoInfo;
import com.cyou.qb.face.entity.trans.FeedChannel;
import com.cyou.qb.face.entity.trans.GameInfoList;
import com.cyou.qb.face.entity.trans.NewsResult;
import com.cyou.qb.face.entity.trans.ReplyInfoCheck;
import com.cyou.qb.face.entity.trans.ReturnGameInfo;
import com.cyou.qb.face.entity.trans.VlogInfo;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.log.IOutServiceLog;
import com.cyou.qb.face.service.GetGameInfoService;
import com.cyou.qb.face.util.contants.FaceContants;
import com.cyou.qb.face.util.converter.FaceHttpUtil;
import com.cyou.qb.face.util.converter.FaceStringUtil;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;

@Service("GetGameInfoServiceImpl")
public class GetGameInfoServiceImpl extends BaseFaceServiceimpl implements GetGameInfoService{
	private final Logger logger = Logger.getLogger(GetGameInfoServiceImpl.class);
	
	@Value("${face.SNSURL}")
	private String faceSNSURL;
	
	@Value("${face.qbWebURL}")
	private String qbWebURL;
	
	@Value("${face.vlogSearchURL}")
	private String searchURL;
	
	@Value("${face.GAMEURL}")
	private String gameURL;
	
	@Resource(name="OutServiceFailLogImpl")
	private IOutServiceLog outServiceLog;
	
	@Override
	/**
	 * 获取游戏资讯
	 */
	public List<NameValue> getGameNews(String gamecode) throws QbGetDataException {
		/**
		 * 添加切面日志
		 */
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		/**
		 * 装填传出参数
		 */
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("index-name", FaceContants.Get_WEBPAGE);
		map.put("expression", "newGameCode='"+gamecode+"'");
		map.put("page-no", FaceContants.PAGE_NO);
		map.put("page-size",5);
		map.put("sort-reverse", true);
		/**
		 * 生成请求URL
		 */
		String url = FaceStringUtil.createURLString(qbWebURL + "/" + searchURL, map);
		accessLog.setCallServiceParam(url);
		String resultJson = null;
		/**
		 * 放出HTTP get请求
		 */
		try {
			resultJson = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			/**
			 * 获取需要的信息
			 */
			NewsResult newsResult  = JacksonUtil.toObject(resultJson, NewsResult.class);
			List<NameValue> list = new ArrayList<NameValue>();
			for(int i=0;i<FaceContants.WEBPAGE_PAGE_SIZE;i++){
				if(newsResult != null && newsResult.getResults() != null && !(newsResult.getResults().isEmpty())){
					if(i>=newsResult.getResults().size())
						break;
					NameValue namevalue = new NameValue();
					namevalue.setStrValue(newsResult.getResults().get(i).getNewsTitle());
					namevalue.setUrl(newsResult.getResults().get(i).getNewsUrl());
					list.add(namevalue);
				}
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			/**
			 * 讲出错信息记录到数据库中
			 */
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("gamecode="+gamecode);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getGameDynamic throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("getGameDynamic throw Exception" + e.getMessage(),e);

		}
		
	}

	@Override
	/**
	 * 获取游戏视频信息 getGameVideoList
	 */
	public List<VideoInfo> getGameVideoInfo(String gamecode) throws QbGetDataException {
	
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("index-name", FaceContants.GET_VLOG);
		map.put("expression", "gamecode='"+gamecode+"'");
		map.put("page-no", FaceContants.PAGE_NO);
		map.put("page-size", FaceContants.VLOG_PAGE_SIZE);
		map.put("sort-reverse", true);
	    map.put("sort-type", "STRING");
	    map.put("sort-by", "i_addtime");

 		String url = FaceStringUtil.createURLString(qbWebURL + "/" + searchURL, map);
		accessLog.setCallServiceParam(url);
		String resultJson = null;
		try {
			resultJson = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			VlogInfo vlogInfo = Jackson2Util.toObject(resultJson, VlogInfo.class);
			List<VideoInfo> list = new ArrayList<VideoInfo>();
			for(int i=0;i< FaceContants.VLOG_PAGE_SIZE;i++){
				if(vlogInfo != null && vlogInfo.getResults() != null && !(vlogInfo.getResults().isEmpty())){
					if(i>=vlogInfo.getResults().size())
						break;
					VideoInfo videoInfo = new VideoInfo();
					videoInfo.setGamecode(vlogInfo.getResults().get(i).getGamecode());
					videoInfo.setVideoLink(vlogInfo.getResults().get(i).getUrl());
					videoInfo.setVideoPicLink(vlogInfo.getResults().get(i).getPicurl());
					videoInfo.setVideoTitle(vlogInfo.getResults().get(i).getTitle());
					list.add(videoInfo);
				}
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();

			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("gamecode="+gamecode);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);

			logger.error("getGameVideoInfo throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("getGameVideoInfo throw Exception" + e.getMessage(),e);
		}
	}
	/**
	 * 通过PHP获取前台主题游戏相关信息 getGameInfoByGameCode
	 * @param gamecode 
	 */
	@Override
	public GameInfo getFrontGameInfo(String gamecode) throws QbGetDataException{
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		accessLog.setCallServiceParam(gameURL);
		
		ReturnGameInfo returnGameInfo = null;
		FeedChannel feedChannel = null;
		try{
			/**
			 * 通过jsonRpc获取游戏信息
			 */
			JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(gameURL));
			returnGameInfo = client.invoke("getGameInfoByGameCode", new Object[] {gamecode}, ReturnGameInfo.class);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog("getGameInfoByGameCode:"+returnGameInfo.toString());

			/**
			 * 通过httpclient 调用feed获取游戏游戏图片
			 */
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("gameId", gamecode);
			map.put("apikey", FaceContants.API_KEY);
			map.put("ver", FaceContants.API_VERSION);
			map.put("method", "FeedCMS.queryFeedChannel");
			String url = FaceStringUtil.createURLString(faceSNSURL, map);
			String resultJson = null;
			resultJson = FaceHttpUtil.doRequest(url, null, null,"UTF-8");
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			
			@SuppressWarnings("rawtypes")
			ReplyInfoCheck ric = JacksonUtil.toObject(resultJson, ReplyInfoCheck.class);
			feedChannel = JacksonUtil.toObject(JacksonUtil.toJson(ric.getData()),FeedChannel.class);
			GameInfo gameInfo = new GameInfo();
			if(returnGameInfo != null){
				gameInfo.setGameBBSLink(returnGameInfo.getBbs_url());
				gameInfo.setGamecode(gamecode);
				if(returnGameInfo.getDevelopers() != null){
					gameInfo.setGameDeveloper(returnGameInfo.getDevelopers().get("name").toString());
				}
				gameInfo.setGameDownLoadLink(returnGameInfo.getDownload_url());
				gameInfo.setGameLink(returnGameInfo.getOfficial_url());
				gameInfo.setGameName(returnGameInfo.getName());
				if(returnGameInfo.getOperators() != null){
					gameInfo.setGameOperator(returnGameInfo.getOperators().get("name").toString());
				}
				if(returnGameInfo.getGame_type() != null){
					gameInfo.setGameType(returnGameInfo.getGame_type().get("name").toString());
				}
				gameInfo.setGameZoneLink(returnGameInfo.getHao_url());
				if(feedChannel != null){
					gameInfo.setIconLink(feedChannel.getBigAvatar());
				}
			}

			return gameInfo;
		}catch(Throwable t){
			t.printStackTrace();
			OutService outService = new OutService();
			outService.setService(gameURL);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("gamecode:"+gamecode);
			outService.setMethod(this.getClass().getName());
			outService.setMemo("gameInfo get fail");
			outServiceLog.saveOutServiceFail(outService);

			logger.error("getFrontGameInfo throw Throwable" + t.getMessage(),t);
			throw new QbGetDataException("getFrontGameInfo throw Throwable" + t.getMessage(),t);
			
		}
		
	}

	@Override
	/**
	 * 获取后台添加活动时所需要的游戏信息
	 * getGameInfoByGameCode
	 */
	public GameInfo getGameInfo(String gamecode) throws QbGetDataException {
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		ReturnGameInfo returnGameInfo = null;
		
		try{
			JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(gameURL));
			accessLog.setCallServiceParam(gameURL);
			returnGameInfo= client.invoke("getGameInfoByGameCode", new Object[] {gamecode,new String[]{"game_type","download_url","operators","developers","bbs_url","download_url","official_url","hao_url"}}, ReturnGameInfo.class);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog("getGameInfoByGameCode " + returnGameInfo.toString());
			GameInfo gameInfo = new GameInfo();
			gameInfo.setGameBBSLink(returnGameInfo.getBbs_url());
			gameInfo.setGamecode(gamecode);
			if(returnGameInfo.getDevelopers() != null){
				gameInfo.setGameDeveloper(returnGameInfo.getDevelopers().get("name").toString());
			}
			gameInfo.setGameDownLoadLink(returnGameInfo.getDownload_url());
			gameInfo.setGameLink(returnGameInfo.getOfficial_url());
			gameInfo.setGameName(returnGameInfo.getName());
			if(returnGameInfo.getOperators() != null){
				gameInfo.setGameOperator(returnGameInfo.getOperators().get("name").toString());
			}
			if(returnGameInfo.getGame_type() != null){
				gameInfo.setGameType(returnGameInfo.getGame_type().get("name").toString());
			}
			gameInfo.setGameZoneLink(returnGameInfo.getHao_url());

			return gameInfo;
		}catch(Throwable t){
			OutService outService = new OutService();
			outService.setService(gameURL);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("gamecode:"+gamecode);
			outService.setMethod(this.getClass().getName());
			outService.setMemo("gameInfo get fail");
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getFrontGameInfo throw Throwable:" + t.getMessage(),t);
			throw new QbGetDataException("getFrontGameInfo throw Throwable:" + t.getMessage(),t);
		}
		
	}

	@Override
	/**
	 * 获取游戏列表  getGameList
	 */
	public List<NameValue> getGameNameInfo() throws QbGetDataException {
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		accessLog.setCallServiceParam(gameURL);

		GameInfoList gameInfoList = null;  
		try{
			
			JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(gameURL));
			gameInfoList = client.invoke("getGameList", new Object[] {1, null,null,5000,null,null}, GameInfoList.class);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog("getGameList: "+ gameInfoList.toString());
			return toNameValues(gameInfoList);
		}catch(Throwable t){
			OutService outService = new OutService();
			outService.setService(gameURL);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject(FaceContants.FAIL_GAME+"");
			outService.setMethod(this.getClass().getName());
			outService.setMemo("gameInfo get fail");
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getGameNameInfo throw Throwable" + t.getMessage(),t);
			throw new QbGetDataException("getGameNameInfo throw Throwable" + t.getMessage(),t);
		}
		
		
	}
	
	/**
	 * json对象转换NameValue
	 * @param gameInfoList
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private List<NameValue> toNameValues(GameInfoList gameInfoList){
		List<NameValue> dataSet = new ArrayList<NameValue>();
		@SuppressWarnings("unchecked")
		List<LinkedHashMap> dataTmp = gameInfoList.getDataSet();
		for(LinkedHashMap obj : dataTmp){
			int status =0;
			try {
				status = Integer.parseInt(obj.get("status").toString());
			} catch (NumberFormatException e) {
			}
			if(status==0)
				continue;
			NameValue nv = new NameValue();
			nv.setStrName(obj.get("name").toString());
			nv.setStrValue(obj.get("game_code").toString());
			dataSet.add(nv);
		}
		return dataSet;
	}
	

	@Override
	/**
	 * 获取游戏类型信息 getAllGameClass
	 */
	public List<NameValue> getGameTypeInfo() throws QbGetDataException {
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		List<NameValue> list1 = new ArrayList<NameValue>();
		try {
			JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(gameURL));
			accessLog.setCallServiceParam(gameURL);
			Map<String,String> data = client.invoke("getAllGameClass", new Object[]{}, Map.class);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog("getAllGameClass:" + data.toString());
			for(String key : data.keySet()){
				NameValue namevalue = new NameValue("",data.get(key),"");
				list1.add(namevalue);
			}
			return list1;
		} catch (Throwable t) {
			OutService outService = new OutService();
			outService.setService(gameURL);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject(FaceContants.FAIL_GAME+"");
			outService.setMethod(this.getClass().getName());
			outService.setMemo("GameTypeInfo get fail");
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getGameTypeInfo throw Throwable" + t.getMessage(),t);
			throw new QbGetDataException("getGameTypeInfo throw Throwable" + t.getMessage(),t);
		}
		
	}
	/**
	 * 根据gamecode获取gameId
	 * @param gamecode
	 * @return
	 * @throws QbGetDataException
	 */
//	private int getGameIdByGameCode(String gamecode) throws QbGetDataException{
//		Integer gameId = null; 
//		Face173AccessLog accessLog = getAccessLog();
//		accessLog.setCallService(this.getClass().getName());
//		try {
//			JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(facePHPURL +"/"+gameInfoURL));
//			accessLog.setCallServiceParam(facePHPURL +"/"+gameInfoURL);
//		gameId = client.invoke("getGameIdByGameCode", new Object[]{gamecode}, Integer.class);
//			
//		} catch (Throwable t) {
//			OutService outService = new OutService();
//			outService.setService(facePHPURL +"/"+gameInfoURL);
//			outService.setType(FaceContants.FAIL_GAME);
//			outService.setObject(gamecode);
//			outService.setMethod(this.getClass().getName());
//			outService.setMemo("getGameIdByGameCode get fail");
//			outServiceFailDAO.saveOutServiceFail(outService);
//			logger.info("getGameIdByGameCode throw Throwable" + t.getMessage());
//			throw new QbGetDataException("getGameIdByGameCode throw Throwable" + t.getMessage());
//		}
//		return gameId;
//	}
}
